package com.hotline.communication.service.impl;


import com.hotline.communication.constants.DateConstant;
import com.hotline.communication.mapper.OrderSeqMapper;
import com.hotline.communication.entity.OrderSeq;
import com.hotline.communication.service.OrderSeqService;
import com.hotline.communication.util.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.Objects;

@Service
@Slf4j
public class OrderSeqServiceImpl implements OrderSeqService {

    @Resource
    private OrderSeqMapper orderSeqMapper;

    @Override
    @Transactional
    public synchronized String getSeq(String seqName,int length) {
        OrderSeq orderSeq =  orderSeqMapper.selectById(seqName);
        Integer orderSn = 1;
        if(Objects.isNull(orderSeq)){
            orderSeq = new OrderSeq();
            orderSeq.setSeqName(seqName);
            orderSeq.setOrderSn(1);
            orderSeqMapper.insert(orderSeq);
        }else{
            orderSeq.setOrderSn(orderSeq.getOrderSn()+1);
            orderSeqMapper.update(orderSeq);
            orderSn = orderSeq.getOrderSn();
        }

        String format = getFormat(length);
        DecimalFormat df = new DecimalFormat(format);
        return df.format(orderSn);
    }


    @Override
    @Transactional
    public synchronized String getSeq(int length) {
        String dateStr = DateUtils.format(new Date(), DateConstant.PURE_DATE);

        return getSeq(dateStr,length);
    }

    private synchronized String getFormat(int length){
        StringBuffer sb = new StringBuffer();
        for(int i=0;i<length;i++){
            sb.append("0");
        }
        return sb.toString();
    }
}
